import { LoadingOutlined, UploadOutlined } from '@ant-design/icons'
import { useUpload } from '@hooks/useUpload'
import { useConfigsUpdateMutation } from '@services/configs'
import { Button, Form, Image, Input, Space } from 'antd'
import React, { useEffect, useState } from 'react'

export default function SystemConfig({ items }) {
  const [form] = Form.useForm()
  const [options, setOptions] = useState(items)
  const { mutate: onFinish } = useConfigsUpdateMutation()

  const { loading, onClick: handleUpload } = useUpload({
    onSuccess: (target, response, fileinfo) => {
      const { key, index } = target.dataset
      console.log('%c Line:15 🍤 key', 'color:#7f2b82', key, index)
      console.log('%c Line:16 🌶 response', 'color:#ea7e5c', response, fileinfo)
      setOptions((prev) => {
        const arr = [...prev]
        arr[index].value = response.url
        return arr
      })
      form.setFieldsValue({ [key]: response.url })
    },
  })

  useEffect(() => {
    if (items && items.length > 0) {
      const result = items.reduce((acc, cur) => ((acc[cur.key] = cur.value), acc), {})
      form.setFieldsValue(result)
    }
  }, [items, form])

  const onFailed = (errorInfo) => {
    console.log('Failed:', errorInfo)
  }

  return (
    <Form
      name="basic"
      labelCol={{ span: 4 }}
      wrapperCol={{ span: 16 }}
      style={{ maxWidth: '80%' }}
      initialValues={{ remember: true }}
      form={form}
      onFinish={onFinish}
      onFinishFailed={onFailed}
      autoComplete="off">
      {options.map((item, index) => (
        <Form.Item
          key={item.key}
          label={item.name}
          name={item.key}
          rules={[{ required: true, message: '请输入' + item.name + '!' }]}>
          <div>
            {item.key.includes('_url') ? (
              <React.Fragment key={item.key}>
                <Space.Compact style={{ width: '100%' }}>
                  <Input size="large" value={item.value} readOnly />
                  <Button
                    size="large"
                    type="primary"
                    icon={loading?.[item.key] ? <LoadingOutlined spin /> : <UploadOutlined />}
                    data-index={index}
                    data-key={item.key}
                    onClick={(e) => handleUpload(e, item.key)}
                  />
                </Space.Compact>
                <div className="mt-2">
                  <Image
                    className="rounded border border-gray-300/30"
                    width={200}
                    src={item.value}
                  />
                </div>
              </React.Fragment>
            ) : (
              <Input
                size="large"
                value={item.value}
                disabled={item.key.includes('_url')}
                onChange={(e) => {
                  setOptions((prev) => {
                    const arr = prev.filter((i) => i.id !== item.id)
                    arr.splice(index, 0, { ...prev[index], value: e.target.value })
                    return arr
                  })
                  form.setFieldsValue({ [item.key]: e.target.value })
                }}
              />
            )}
            {/* if image or file, and need to show upload btn */}

            <p style={{ fontSize: 12, color: 'gray', opacity: 0.4 }}>{item.desc}</p>
          </div>
        </Form.Item>
      ))}

      <Form.Item label={null}>
        <Button size="large" type="primary" htmlType="submit" className="w-full">
          保 存
        </Button>
      </Form.Item>
    </Form>
  )
}
